from app.util import parse_arg, Config
from app.ai_chater import AiChater

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QLineEdit, QPushButton
import sys


class AiChatWindow(QWidget):
    def __init__(self, config: Config):
        super().__init__()
        self.setWindowTitle("AI Chat Assistant")
        self.setGeometry(100, 100, 600, 400)

        self.layout = QVBoxLayout()

        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)

        self.input_line = QLineEdit()
        self.input_line.returnPressed.connect(self.send_message)

        self.send_button = QPushButton("发送")
        self.send_button.clicked.connect(self.send_message)

        self.layout.addWidget(self.chat_display)
        self.layout.addWidget(self.input_line)
        self.layout.addWidget(self.send_button)
        self.setLayout(self.layout)

        self.ai_chater = AiChater(config)

        self.add_ai_message('我是一个 AI 小助手，我可以帮您做什么？')

    def send_message(self):
        user_input = self.input_line.text().strip()
        if not user_input:
            return

        self.add_human_message(user_input)
        self.input_line.clear()

        ai_output = self.ai_chater.invoke(user_input)

        self.add_ai_message(ai_output)

    def add_ai_message(self, msg: str):
        self.chat_display.append(f"<b>AI：</b> {msg}\n")

    def add_human_message(self, msg: str):
        self.chat_display.append(f"<b>你：</b> {msg}\n")


def main(config: Config):
    app = QApplication(sys.argv)
    window = AiChatWindow(config)
    window.show()
    sys.exit(app.exec_())